package com.masterstroke.template.controller;


import com.masterstroke.template.common.constant.MessageConstant;
import com.masterstroke.template.common.context.JwtClaimsConstant;
import com.masterstroke.template.common.exception.BaseException;
import com.masterstroke.template.common.properties.JwtProperties;
import com.masterstroke.template.common.result.Result;
import com.masterstroke.template.common.utils.Encipher;
import com.masterstroke.template.common.utils.JwtUtil;
import com.masterstroke.template.pojo.domain.User;
import com.masterstroke.template.pojo.dto.UserLoginDTO;
import com.masterstroke.template.pojo.vo.UserLoginVO;
import com.masterstroke.template.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController("user")
@RequestMapping("user")
@Api("user相关接口")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){

        log.info("登录：{}", userLoginDTO);

        User user = userService.login(userLoginDTO);

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUserName())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public Result<String> register(String username, String password) {
        User user= userService.getUserByName(username);
        if (user != null){
            throw new BaseException(MessageConstant.ALREADY_EXISTS);
        }
        String passwordUuid = Encipher.getUUID(password);
        String uuid = Encipher.getUUID();

        User user1 = new User();
        user1.setUserPassword(passwordUuid);
        user1.setUserName(username);
        user1.setId(uuid);

        userService.save(user1);
        return Result.success();
    }

    @ApiOperation("删除用户")
    @PostMapping("/deleteUser")
    public Result<String> deleteUser(String id) {
        userService.removeById(id);
        return Result.success(MessageConstant.SUCCESS);
    }

    @ApiOperation("获取所有用户")
    @GetMapping("getAllUser")
    public Result<List<User>> getAllUser() {
        return Result.success(userService.list());
    }

}
